package cn.yeziji.netty.adapter;

import cn.yeziji.forum.basic.netty.Message;
import cn.yeziji.forum.basic.netty.user.UserMessage;
import cn.yeziji.forum.common.key.NoticeCacheKey;
import cn.yeziji.forum.common.key.RabbitMQConfig;
import cn.yeziji.forum.utils.ListsCollect;
import cn.yeziji.forum.utils.RedisUtils;
import cn.yeziji.netty.config.handler.NettyWebsocketHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户登录适配器
 *
 * @author gzkemays
 * @since 2022/11/08 10:21 AM
 */
@Slf4j
public class UserLoginAdapter extends SelectedTypes<UserMessage> implements CommunicationAdapters {
  RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
  RedisUtils redisUtils = new RedisUtils(redisTemplate);

  RabbitTemplate rabbitTemplate = getRabbitTemplate();

  public UserLoginAdapter(Integer type, String text) {
    super(type, text, UserMessage.class);
    if (this.data != null) {
      // 等于 null 是无登录连接
      this.data.setFlag(true);
    }
  }

  @Override
  public void notice(ChannelHandlerContext channelHandlerContext) {
    if (this.data != null) {
      log.info("用户 {} 登录", data.getNickname());
      NettyWebsocketHandler nettyWebsocketHandler = getNettyWebsocketHandler();
      // 通知 rabbitMQ 有用户登录了
      rabbitTemplate.convertAndSend(
          RabbitMQConfig.USER_MSG_EXCHANGE, RabbitMQConfig.USER_MSG_ROUTING_KEY, data);
      // 加入 channel 和 用户信息关联
      Map<ChannelHandlerContext, UserMessage> connectUserMsg =
          nettyWebsocketHandler.getConnectUserMsg();
      connectUserMsg.put(channelHandlerContext, data);
    } else {
      log.info("未登录用户连接");
    }
  }

  @Override
  public List<Message> dispose(ChannelHandlerContext channelHandlerContext) {
    if (this.data != null) {
      log.info("用户 {} 登录后消息处理", data.getNickname());
      String nickname = data.getNickname();
      List<Message> noticeMessages =
          ListsCollect.castList(
              redisUtils.list0Range(NoticeCacheKey.UN_READ + data.getUsername()), Message.class);
      log.info("用户 {} 以下消息未处理：{}", nickname, noticeMessages);
      // 移动至已读
      //    readMessage(data.getUsername(), noticeMessages);
      // 重新计算时间
      for (Message noticeMessage : noticeMessages) {
        noticeMessage.buildNoticeTime(new Date());
      }
      // 发送数据
      writeAndFlushMessage(channelHandlerContext, noticeMessages);
      return noticeMessages;
    }
    return null;

    //    long chat = 0, detail = 0;
    //    // 遍历离线时，有人发送聊天信息给你的数据
    //    chat += redisUtils.getHashSize(getChatLeaveCacheKey(nickname));
    //    // 遍历在线时，有人发送聊天信息给你的数据
    //    Set<String> onlineKeys = redisUtils.blurHasKey(getChatOnlineCacheKey(nickname));
    //    for (String onlineKey : onlineKeys) {
    //      chat += redisUtils.getHashSize(onlineKey);
    //    }
    //    // 获取文章发布的信息
    //    detail += redisUtils.getHashSize(getDetailNoticeCacheKey(nickname));
    //    UnreadStatistics unreadStatistics = new UnreadStatistics(chat, detail);
    //    // 将统计信息返回给当前用户
    //    channelHandlerContext.writeAndFlush(
    //        new TextWebSocketFrame(JSON.toJSONString(unreadStatistics)));
  }
}
